package com.triple.triplerpc.fault.tolerant;

import com.triple.triplerpc.model.RpcRequest;
import com.triple.triplerpc.model.RpcResponse;
import com.triple.triplerpc.proxy.ServiceProxyFactory;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 失败自动恢复策略实现类 - 容错策略
 */
@Slf4j
public class FailBackTolerantStrategy implements TolerantStrategy {

    @Override
    public RpcResponse doTolerant(Map<String, Object> context, Exception e) throws Exception {
        System.out.println(" >>> 当前采用的容错机制 - 失败自动恢复, 调用Mock接口");
        // 通过context里的信息, 获取降级接口
        RpcRequest rpcRequest = (RpcRequest) context.getOrDefault("rpcRequest", null);
        if (rpcRequest == null) {
            log.info("失败自动恢复策略无法获取请求上下文: ", e);
            throw new RuntimeException(e.getMessage());
        }
        String serviceName = rpcRequest.getServiceName();
        Class<?> serviceClass = Class.forName(serviceName);
        // 降级使用mock接口
        Object mockProxy = ServiceProxyFactory.getMockProxy(serviceClass);
        Method method = mockProxy.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object result = method.invoke(mockProxy, rpcRequest.getArgs());
        // 返回结果
        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setData(result);
        rpcResponse.setDataType(method.getReturnType());
        rpcResponse.setMessage("使用失败自动恢复容错策略调用Mock接口");
        return rpcResponse;
    }

}
